<?php
	function get_group_data_as_array($path, $group_name) {
		$file = file($path);
		$erste_zeile = true;
		$result = array();
		$i=0;
		foreach($file as $line) {			
			$to_array = explode("\t",$line);
			if($to_array[1] == $group_name) {
				$result[$i++] = $to_array;
			}
		}
		return $result;
	}
	function get_group_start_point(&$group_data) {
		foreach($group_data as $d) {
			if($d[6]=="1") {
				if(($key = array_search($d, $group_data)) !== false) {
					unset($group_data[$key]);
				}
				return $d;
			}
		}
	}
	
	function get_group_data_as_csv($path, $group_name) {
		$group_data = get_group_data_as_array($path, $group_name);
		$csv = array_implode("\n",",", $group_data );
		return $csv;
	}
	
	/**
	 * Implode an array with the key and value pair giving
	 * a glue, a separator between pairs and the array
	 * to implode.
	 * @param string $separator Separator between pairs
	 * @param array $array The array to implode
	 * @return string The imploded array
	 */
	function array_implode($glue, $separator, $array ) {
		if ( ! is_array( $array ) ) return $array;
		$string = array();
		foreach ( $array as $key => $val ) {
			if ( is_array( $val ) )
				$val = implode( $separator, $val );
			$string[] = "{$val}";

		}
		return implode($glue, $string );
	}
	/**
	 * Reduziert ein zweidimensionales Array zu einem Eindimensionalem Array
	 * @param string $separator Gibt das Trennzeichen der Werte an
	 * @param array $array das Multidimensionale Array
	 * @return eindimensionales array
	 */
	function reduce_dimension($separator, $array) {
		if ( ! is_array( $array ) ) return $array;
		$single_array = array();
		foreach ( $array as $key => $val ) {
			if ( is_array( $val ) )
				$val = implode( $separator, $val );
			$single_array[] = $val;

		}
		return $single_array;
	}
	
	function refresh_coordinates($path, $name, $long, $lat, $time, $height, $group, $is_start) {
		if (($handle = fopen($path, "r")) !== FALSE) {
			$all_data = array();
			$i=0;
			$set_exists = false;
			while (($data = fgetcsv($handle, 1000, "\t")) !== FALSE) {
				
				// Customer ID exists so edit the record
				if($data[0] == $name && $data[1] == $group){
					$data[2] = $long;
					$data[3] = $lat;	            
					$data[4] = $time;
					$data[5] = $height;
					$set_exists=true;
				}
				$all_data[$i++] = $data;				
			}
			//neu anlegen wenn es nicht existiert
			if(!$set_exists) {
				$data[0] = $name;
				$data[1] = $group;
				$data[2] = $long;
				$data[3] = $lat;	            
				$data[4] = $time;
				$data[5] = $height;
				$data[6] = $is_start;
				$all_data[$i++] = $data;
			}
			fclose($handle);
		}
		if (($handle = fopen($path, "w")) !== FALSE) {
			foreach($all_data as $line) {
				fputcsv($handle, $line,"\t",'"');
			}
			fclose($handle);
		}
	}
?>